import { getChannel } from "@/utils/channel";
import wechatOa from "@/utils/wechat";
import { ChannelEnum } from "@/enums/channelEnum";
import { PayStatusEnum } from "@/enums/payEnum";

const wxpay = async (params: any) => {
    const channelVal = getChannel();

    try {
        switch (channelVal) {
            case channelVal == ChannelEnum.WX_AP:
                return new Promise((resolve, reject) => {
                    uni.requestPayment({
                        provider: 'wxpay',
                        ...params,
                        success(res) {
                            res.callPayStatus = PayStatusEnum.SUCCESS
                            resolve(res)
                        },
                        complete(res) {
                            if (res.errMsg == 'requestPayment:cancel' || res.errMsg == 'requestOrderPayment:cancel') {
                                res.callPayStatus = PayStatusEnum.CANCEL
                                reject(res)
                            }
                        },
                        fail(res) {
                            res.callPayStatus = PayStatusEnum.FAIL
                            reject(res)
                        }
                    })
                })
                break;
            case channelVal == ChannelEnum.WX_OA:
                return new Promise((resolve, reject) => {
                    wechatOa.pay(params)
                        .then((res) => {
                            resolve(res)
                        })
                        .catch((res) => {
                            reject(res)
                        })
                })
                break;
            case channelVal == ChannelEnum.H5:
                return new Promise((resolve) => {
                    location.replace(params.h5_url);
                    resolve({ callPayStatus: PayStatusEnum.PENDING })
                })
                break;
            case channelVal == ChannelEnum.APP:
                return new Promise((resolve, reject) => {
                    uni.requestPayment({
                        provider: 'wxpay',
                        orderInfo: params.orderInfo,
                        success(res) {
                            res.callPayStatus = PayStatusEnum.SUCCESS
                            resolve(res)
                        },
                        fail(res) {
                            res.callPayStatus = PayStatusEnum.FAIL
                            reject(res)
                        }
                    })
                })
                break;
            default:
                break;
        }
    } catch (error) {
        error.callPayStatus = PayStatusEnum.ERROR
        return Promise.reject(error)
    }
}

export default wxpay;